// 如果一个岛屿没有被包裹，那么就是独立的岛屿
// 如何判断是否被包裹，看看能不能通过0走到边界，从任意一个地方走即可
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;

const int N = 55;
int a[N][N];
int n, m;
bool st[N][N];
bool water[N][N];
int num = 0;
int have_ans = false;
int dx[8] = {0, 1, 0, -1, 1, 1, -1, -1};
int dy[8] = {1, 0, -1, 0, -1, 1, 1, -1};

void dfs(int x, int y)
{
    st[x][y] = true;
    for(int i = 0; i < 4; ++i)
    {
        int xx = x + dx[i], yy = y + dy[i];
        if(xx > 0 && xx <= n && yy > 0 && yy <= m && a[xx][yy] && !st[xx][yy])
            dfs(xx, yy);
    }
}

void dfs_go(int x, int y)
{
    if(x <= 0 || x > n || y <= 0 || y > m)
    {
        have_ans = true;
        return;
    }
    water[x][y] = true;
    for(int i = 0; i < 8; ++i)
    {
        int xx = x + dx[i], yy = y + dy[i];
        if(!a[xx][yy] && !water[xx][yy])
            dfs_go(xx, yy);
        if(have_ans) return;
    }
}

void print()
{
    for(int i = 1; i <= n; ++i)
    {
        for(int j = 1; j <= m; ++j)
            cout << a[i][j];
        cout << endl;
    }
}

int main()
{
    int T;
    cin >> T;
    for(int g = 0; g < T; ++g)
    {
        num = 0;
        memset(st, 0, sizeof st);
        memset(a, 0, sizeof a);
        cin >> n >> m;
        for(int i = 1; i <= n; ++i)
        {
            string s;
            cin >> s;
            for(int j = 1; j <= m; ++j)
                a[i][j] = s[j - 1] - '0';
        }
        for(int i = 1; i <= n; ++i)
            for(int j = 1; j <= m; ++j)
            {
                // 如果还没走过，这是一个新岛屿
                if(a[i][j] && !st[i][j])
                {
                    dfs(i, j);
                    // 判断这个岛屿有没有被包围
                    for(int t = 0; t < 8; ++t)
                    {
                        int xx = i + dx[t], yy = j + dy[t];
                        if(xx <= 0 || xx > n || yy <= 0 || yy > m)
                        {
                            have_ans = true;
                            break;
                        }
                        else if(!a[xx][yy])
                        {
                            memset(water, 0, sizeof water);
                            dfs_go(xx, yy);
                            if(have_ans) break;
                        }
                    }
                    if(have_ans) ++num;
                    have_ans = false;
                }
            }
        cout << num << endl;
    }
    return 0;
}
